﻿using Microsoft.WindowsAzure.Storage.Table;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CloudStorageLight.Core
{
    public class FileAccessLog : TableEntity
    {
        public FileAccessLog()
        {

        }

        private string GetPathHash(string s)
        {            
            var bytes = System.Text.Encoding.UTF8.GetBytes(BlobItem.GetDirectoryPath(s));
            var hash = new System.Security.Cryptography.MD5CryptoServiceProvider().ComputeHash(bytes);
            return Convert.ToBase64String(hash).Replace("/","").Replace("#","").Replace("=", "");
        }
        public FileAccessLog(string accountName, string path, string rowkey)
        {
            var guid = Guid.NewGuid();

            this.PartitionKey = (accountName ?? "") + "_" + GetPathHash(path);
            this.RowKey = rowkey;
            this.Path = path;
        }

        public DateTime Date
        {
            get
            {
                var d = DateTime.ParseExact(this.RowKey.Split('-')[0], "yyyyMMdd HH:mm:ss:fff", null, System.Globalization.DateTimeStyles.AssumeUniversal);
                return d;
            }
        }

        public string Path { get; set; }
        public string UserName { get; set; }


        public string AccountName
        {
            get
            {
                return this.PartitionKey.Split('\\')[0];
            }
        }

        public string Action { get; set; }

        public string IPAddress { get; set; }


    }

    public class MarkFileAccessLog : TableEntity
    {
        public MarkFileAccessLog()
        {

        }

        public MarkFileAccessLog(string accountName)
        {
            this.PartitionKey = (accountName ?? "");
            this.RowKey = "";
        }

        public string LastUpdatePartitionKey { get; set; }
        public string LastUpdateRowKey { get; set; } 
    }

}
